/**
 * 
 */
package com.tvshows.front.listener.menu;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Listener;

import com.tvshows.front.controllers.dialog.ActionsController;
import com.tvshows.front.ui.menu.MenuUI;

/**
 * @author Tangi Midy
 * <p>
 * Menu item listener class
 * </p>
 */
public class MenuListener
    implements Listener
{
    /**
     * The main view
     */
    private MenuUI menuUI;

    /**
	 * 
	 */
    public MenuListener( MenuUI menuUI )
    {
        this.menuUI = menuUI;
    }

    /**
     * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
     */
    @Override
    public void handleEvent( Event e )
    {

        // Log
        if ( e.widget == menuUI.getLogItem() )
        {
            ActionsController.openLog( menuUI );
        }

        // Options
        else if ( e.widget == menuUI.getOptionsItem() )
        {
            ActionsController.openOptions( menuUI.getMainView() );
        }

        // exportXml
        else if ( e.widget == menuUI.getExportXmlItem() )
        {
            ActionsController.exportXML( browseDialog() );
            menuUI.showSuccess();
        }

        // ImportXml
        else if ( e.widget == menuUI.getImportXmlItem() )
        {
            if ( ActionsController.importXml( browseDialog() ) )
            {
                menuUI.showSuccess();
            }
            else
            {
                menuUI.showFailure();
            }
        }

        // Active Sql
        else if ( e.widget == menuUI.getActiveSqlItem() )
        {
            ActionsController.activeSql();
        }

        // Quitter
        else if ( e.widget == menuUI.getQuitterItem() )
        {
            ActionsController.exit();

        }

    }

    /**
     * Opens the browsing dialog
     */
    private String browseDialog()
    {
        FileDialog fDialog = new FileDialog( menuUI.getMainView().getShell(), SWT.SAVE );
        fDialog.setFilterNames( new String[] { "Xml Files (*.xml)", } );
        fDialog.setFilterExtensions( new String[] { "*.xml" } ); // Windows

        return fDialog.open();
    }

}
